package com.taotao.jdk01;

import com.taotao.entity.UserEntity;
import com.taotao.utils.MayiktJdbcUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Insert;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @Author: wangjin
 * @CreateTime: 2022-08-06  17:24
 */
@Slf4j
public class MybatisJdkInvocationHandler implements InvocationHandler {
    private Class mapperClass;

    public MybatisJdkInvocationHandler(Class mapperClass) {
        this.mapperClass = mapperClass;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //使用java反射技术获取方法上的注解
        System.out.println("调用到该方法");
        //使用我们的方法上的@Insert注解对应的insert sql
        Insert declareInsert = method.getDeclaredAnnotation(Insert.class);
        String[] value = declareInsert.value();
         String insertSql=value[0];
         //jdbc 技术执行的sql语句
           Connection con= MayiktJdbcUtils.getConnection();
        PreparedStatement preparedStatement=con.prepareStatement(insertSql);
        return  preparedStatement.executeUpdate();

    }

    public <T> T getProxy() {
        return (T) Proxy.newProxyInstance(mapperClass.getClassLoader(), new Class[]{mapperClass}, this);
    }
}
